package com.daffodil.devtool.controller;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.daffodil.core.annotation.AuthPermission;
import com.daffodil.core.annotation.Log;
import com.daffodil.core.annotation.Log.BusinessType;
import com.daffodil.core.controller.ReactiveBaseController;
import com.daffodil.core.entity.JsonResult;
import com.daffodil.core.entity.Page;
import com.daffodil.core.entity.TableInfo;
import com.daffodil.devtool.constant.DevtoolConstant;
import com.daffodil.devtool.entity.GenTable;
import com.daffodil.devtool.service.IGenTableService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import reactor.core.publisher.Mono;
import springfox.documentation.annotations.ApiIgnore;

/**
 * 
 * @author yweijian
 * @date 2022年2月28日
 * @version 1.0
 * @description
 */
@Api(value = "数据库表管理", tags = "数据库表管理")
@RestController
@RequestMapping(DevtoolConstant.API_CONTENT_PATH)
public class GenTableController extends ReactiveBaseController {

    @Autowired
    private IGenTableService tableService;

    @ApiOperation("分页查询数据库表列表")
    @ApiImplicitParam(name = HttpHeaders.AUTHORIZATION, value = "登录授权令牌 Bearer token", paramType = "header", required = true)
    @SuppressWarnings("unchecked")
    @AuthPermission("devtool:gentable:list")
    @GetMapping("/gentable/list")
    public TableInfo list(GenTable table, Page page, @ApiIgnore ServerHttpRequest request) {
        initQuery(table, page, request);
        List<GenTable> list = tableService.selectGenTableList(query);
        return initTableInfo(list, query);
    }


    @ApiOperation("新增数据库表")
    @ApiImplicitParam(name = HttpHeaders.AUTHORIZATION, value = "登录授权令牌 Bearer token", paramType = "header", required = true)
    @AuthPermission("devtool:gentable:add")
    @Log(title = "数据库表管理", businessType = BusinessType.INSERT)
    @PostMapping("/gentable/add")
    public JsonResult add(@Validated @RequestBody GenTable table, @ApiIgnore ServerHttpRequest request) {
        tableService.insertGenTable(table);
        return JsonResult.success(table);
    }

    @ApiOperation("修改数据库表")
    @ApiImplicitParam(name = HttpHeaders.AUTHORIZATION, value = "登录授权令牌 Bearer token", paramType = "header", required = true)
    @AuthPermission("devtool:gentable:edit")
    @Log(title = "数据库表管理", businessType = BusinessType.UPDATE)
    @PostMapping("/gentable/edit")
    public JsonResult edit(@Validated @RequestBody GenTable table, @ApiIgnore ServerHttpRequest request) {
        tableService.updateGenTable(table);
        return JsonResult.success();
    }

    @ApiOperation("删除数据库表")
    @ApiImplicitParam(name = HttpHeaders.AUTHORIZATION, value = "登录授权令牌 Bearer token", paramType = "header", required = true)
    @AuthPermission("devtool:gentable:remove")
    @Log(title = "数据库表管理", businessType = BusinessType.DELETE)
    @PostMapping("/gentable/remove")
    public JsonResult remove(@RequestBody String[] ids, @ApiIgnore ServerHttpRequest request) {
        tableService.deleteGenTableByIds(ids);
        return JsonResult.success();
    }
    
    @ApiOperation("预览代码")
    @ApiImplicitParam(name = HttpHeaders.AUTHORIZATION, value = "登录授权令牌 Bearer token", paramType = "header", required = true)
    @AuthPermission("devtool:gencode:preview")
    @GetMapping("/gencode/preview/{tableId}")
    public JsonResult preview(@ApiParam(value = "数据库表ID") @PathVariable("tableId") String tableId, @ApiIgnore ServerHttpRequest request){
        Map<String, String> data = tableService.previewGenTableCode(tableId);
        return JsonResult.success(data);
    }
    
    @ApiOperation("生成代码")
    @ApiImplicitParam(name = HttpHeaders.AUTHORIZATION, value = "登录授权令牌 Bearer token", paramType = "header", required = true)
    @AuthPermission("devtool:gencode:download")
    @Log(title = "数据库表管理", businessType = BusinessType.GENCODE)
    @GetMapping("/gencode/download/{tableId}")
    public Mono<Void> download(@ApiParam(value = "数据库表ID") @PathVariable("tableId") String tableId, @ApiIgnore ServerHttpResponse response, @ApiIgnore ServerHttpRequest request) throws IOException {
        byte[] bytes = tableService.generateGenTableCode(tableId);
        response.getHeaders().set("Content-Disposition", "attachment; filename=\"code_v_" + new Date().getTime() + ".zip\"");
        response.getHeaders().set("Content-Length", "" + bytes.length);
        response.getHeaders().setContentType(MediaType.APPLICATION_OCTET_STREAM);
        DataBuffer dataBuffer = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(dataBuffer));
    }
}
